package com.base.monitor.module.biz.server;

import com.base.monitor.module.biz.util.ConvertUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class LengthMessageDecoder extends ByteToMessageDecoder {

    int length = 0;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        if(buffer.readableBytes() >= 1) {
            if (length == 0) {
                length = buffer.readByte();
            }
            // 当前可读数据不够，继续等待
            if (buffer.readableBytes() < length) {
                return;
            }
            byte[] content = new byte[length];
            if (buffer.readableBytes() >= length) {
                buffer.readBytes(content);
                out.add(ConvertUtils.bytesToHexString(content));
            }
            length = 0;
        }
    }
}
